<?php

/**
 * Created by PhpStorm.
 * User: Lomon
 * Date: 2020/12/03
 * 定时执行 每个月1号分配上一个月的奖金池的奖金
 * 默认 0 6 1 * * 每月1号凌晨6点
 *
 * 每个月1号执行脚本,分配奖金池奖金
    脚本逻辑:
    1.统计上一个月的晋升玩家详情,retail_user.level_time晋升时间
    2.查询retail_reward表获取上一个月的奖金池奖金数
    3.平分奖金给晋升的玩家,记录retail_reward_give_log表
    4.如果上个月没有晋升玩家,则不处理或者累计到下个月(待定)
 */
namespace app\admin\command;

use app\common\model\RetailReward;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;

use app\common\model\RetailUser;
use think\Db;

class Reward extends Command
{
    protected function configure()
    {
        $this->setName('Reward')->setDescription('每个月1号分配上一个月的奖金池的奖金');
    }
    protected function execute(Input $input, Output $output)
    {
        try{
            //1.查询retail_reward表获取上一个月的奖金池奖金数
            $month = date('Ym',strtotime("last month"));
            $reward = db('retail_reward')->where(['month'=>$month])->find();
            if(empty($reward['total'])){
                echo "上个月奖池没有奖金";exit;
            }elseif($reward['status'] != RetailReward::STATUS_ENABLE){
                echo "该奖金已经分配完了";exit;
            }

            //2.统计上一个月的晋升玩家详情,retail_user.level_time晋升时间
            $start_time = strtotime('last month');
            $end_time   = strtotime(date('Y-m-1'));
            $w = ['level_time'=>['between',"$start_time,$end_time"],'level'=>RetailUser::LEVEL_WANJIA,'status'=>RetailUser::STATUS_ENABLE];
            $retual_user = db('retail_user')->where($w)->select();

            $total_user = count($retual_user);//成为玩家的总人数
            if(empty($total_user)){
                //如果上个月没有晋升玩家,则不处理或者累计到下个月(待定)
                echo "上个月没有晋升的玩家";exit;
            }

            /*******3.平分奖金给晋升的玩家,记录retail_reward_give_log表********/

            $avg = round((float)($reward['total'] / $total_user), 2);

            //奖池分配日志data
            $nowtime = time();
            $give_log_data = [];
            $useridsarr = [];
            $wallet_log_data = [];
            foreach ($retual_user as $item){
                $useridsarr[] = $item['uid'];

                $give_log_data[] = [
                    'user_id'   => $item['uid'],
                    'money'     => $avg,
                    'create_time' => $nowtime,
                ];

                $wallet_log_data[] = [
                    'user_id'   => $item['uid'],
                    'wallet'    => $avg,
                    'type'      => "reward_avg",
                    'wallet_type' => 'money',
                    'item_id'   => $reward['id'],
                    'oper_type' => 'system',
                    'createtime' => $nowtime,
                    'updatetime' => $nowtime,
                ];
            }
            Db::startTrans();
            try{
                //修改奖池状态
                db('retail_reward')->where(['month'=>$month])->update(["status"=>RetailReward::STATUS_DISABLE]);

                //分配奖金日志记录
                db('retail_reward_give_log')->insertAll($give_log_data);

                //钱包日志记录
                //db('shopro_user_wallet_log')->insertAll($wallet_log_data);

                //批量更新user.money
                //$userids = implode(",",$useridsarr);
               // $sql = "update fa_user set money = money + {$avg} where id in($userids)";
                //Db::execute($sql);

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                \think\log::error("奖池分配任务失败:".$e->getMessage());
                exit;
            }

        }catch (\Exception $e){
            \think\log::error("奖池分配任务失败:".$e->getMessage());
            exit;
        }

        echo "分配成功";exit;
    }
}